<script setup lang="ts">
import type { ConsultIllness, Image } from '@/types/consult'
import { flagOptions, timeOptions } from '@/services/constants'
import { ref } from 'vue'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { uploadImage } from '@/services/consult'
import { computed } from 'vue'
import { showConfirmDialog, showToast } from 'vant'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
import { onMounted } from 'vue'

const form = ref<ConsultIllness>({
  illnessDesc: '',
  illnessTime: undefined,
  consultFlag: undefined,
  pictures: []
})

// UploaderAfterRead vant内置的函数类型  type UploaderAfterRead = () => void
const afterRead: UploaderAfterRead = async (file) => {
  // 此时可以自行将文件上传至服务器
  console.log('拿到文件啦开始上传啦', file)

  // file可能是个数组?
  if (Array.isArray(file)) return
  if (!file.file) return

  // 上传之前 需要将上传状态改成上传中
  file.message = '上传中...'
  file.status = 'uploading'

  // 确保file身上一定有一个file文件对象
  try {
    const res = await uploadImage(file.file)
    console.log(res) // id  url
    file.url = res.data.url // 更新临时数据的url
    form.value.pictures?.push(res.data) // 更新表单数据

    // 上传之后需要关闭加载状态
    file.message = undefined
    file.status = 'done'
  } catch {
    // 上传失败之后需要关闭加载状态
    file.message = '上传失败'
    file.status = 'failed'
  }
}

const del: UploaderAfterRead = (file) => {
  // .. 删除逻辑
  // file可能是个数组?
  if (Array.isArray(file)) return

  // console.log(file)
  form.value.pictures = form.value.pictures?.filter(
    (item) => item.url !== file.url
  )
}

const fileList = ref<Image[]>([])

// 只有这三个有一个是空  就应该是true 表示禁用
// const disabled = ref(false) // 这个到底是true 还是false 取决于form中前三个字段有没有值
const disabled = computed(() => {
  return !(
    form.value.illnessDesc !== '' &&
    form.value.illnessTime !== undefined &&
    form.value.consultFlag !== undefined
  )
})

const router = useRouter()
const store = useConsultStore()
const next = () => {
  // ...存储store 跳转页面
  // console.log(11)
  // 只是添加了按钮的禁用效果css样式  不妨碍用户继续点击 => 判断
  if (form.value.illnessDesc === '') return showToast('请输入病情描述')
  if (form.value.illnessTime === undefined) return showToast('请选择患病时间')
  if (form.value.consultFlag === undefined) return showToast('请选择是否就诊过')

  // console.log(11)
  store.setIllness(form.value)
  router.push('/user/patient?isChange=1') // 跳转选择患者页面() 家庭档案
}

// -------------------页面加载好了之后 需要让用户主动确认是否恢复信息------------------------
onMounted(() => {
  // 需要判断用户有没有存储过信息 => 存储过 需要给用户一个提示
  if (store.consult.illnessDesc) {
    // 弹出确认框
    showConfirmDialog({
      title: '温馨提示',
      message: '你想要恢复之前的信息么',
      closeOnPopstate: false // 每次回退都弹窗  默认是true 只会第一次返回时打开弹窗
    }).then(() => {
      console.log('点击确认')
      // 数据回显...
      // 确认
      const { illnessDesc, illnessTime, consultFlag, pictures } = store.consult
      form.value = { illnessDesc, illnessTime, consultFlag, pictures }
      // 图片回显
      fileList.value = pictures || []
    })
  }
})
</script>

<template>
  <div class="consult-illness-page">
    <cp-nav-bar title="图文问诊" />
    <!-- 医生提示 -->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 收集信息 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        v-model="form.illnessDesc"
        placeholder="请详细描述您的病情，病情描述不能为空"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn
          :options="timeOptions"
          v-model="form.illnessTime"
        ></cp-radio-btn>
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn
          :options="flagOptions"
          v-model="form.consultFlag"
        ></cp-radio-btn>
      </div>
      <div class="illness-img">
        <!-- 
          1KB = 1024B(字节)
          1M  = 1024KB
         -->
        <van-uploader
          v-model="fileList"
          @delete="del"
          :after-read="afterRead"
          upload-icon="photo-o"
          upload-text="上传图片"
          max-count="9"
          :max-size="1024 * 1024 * 5"
        ></van-uploader>
        <p class="tip">上传内容仅医生可见,最多9张图,最大5MB</p>
      </div>
    </div>

    <van-button
      :class="{ disabled: disabled }"
      @click="next"
      type="primary"
      block
      round
    >
      下一步
    </van-button>
  </div>
</template>

<style lang="scss" scoped>
.van-button {
  font-size: 16px;
  margin-bottom: 30px;
  &.disabled {
    opacity: 1;
    background: #fafafa;
    color: #d9dbde;
    border: #fafafa;
  }
}
.illness-img {
  padding-top: 16px;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }
  ::v-deep() {
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;
          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }
        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }
      &__upload {
        border-radius: 8px;
      }
      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}

.consult-illness-page {
  padding-top: 46px;
}
.illness-tip {
  display: flex;
  padding: 15px;
  .img {
    width: 52px;
    height: 52px;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
  }
  .info {
    flex: 1;
    padding-left: 12px;
    .tit {
      font-size: 16px;
      margin-bottom: 5px;
    }
    .tip {
      padding: 12px;
      background: var(--cp-bg);
      color: var(--cp-text3);
      font-size: 13px;
      margin-bottom: 10px;
    }
    .safe {
      font-size: 10px;
      color: var(--cp-text3);
      display: flex;
      align-items: center;
      .cp-icon {
        font-size: 12px;
        margin-right: 2px;
      }
    }
  }
}
.illness-form {
  padding: 15px;
  .van-field {
    padding: 0;
    &::after {
      border-bottom: none;
    }
  }
  .item {
    > p {
      color: var(--cp-text3);
      padding: 15px 0;
    }
  }
}
</style>
